<?php
function notify_db($out_trade_no,$wx_order) {

    $mysqli = new mysqli("xxxxxxxx", "xxxxxxxx", "xxxxxxxx", "qutiqian_pro");
    $mysqli->query("set names utf8");

    $sql ="select * from `customer_bill_pay_log` where `order_id`='$out_trade_no' and `pay_type` in(2,4) limit 1";
    $result = $mysqli->query($sql);
    $row = $result->fetch_array(MYSQLI_ASSOC);

    if($row['id']>0) {
        $sql = "update `customer_bill_pay_log` set `status`=1,`pay_time`='".time()."',`trade_state`='TRADE_SUCCESS',`ret_code`='0000',`ret_msg`='success',`trade_id`='$wx_order' where `order_id` = '$out_trade_no' and `status`=0";
        $result = $mysqli->query($sql);
        $status = $mysqli->affected_rows;

        $amount = $row['amount'];
        $customerId = $row['customer_id'];
        $consume_id = $row['consume_id'];
        $overdue_amount = $row['overdue_amount'];
        $balance_amount_old = $row['balance_amount_old'];
        $balance_cash_amount_old = $row['balance_cash_amount_old'];
        $credit_level_old = $row['credit_level'];
        $insertId = $row['id'];
        $normal_amount = $amount - $overdue_amount; //本金无利息
        $repay_date = $row['repay_date'];
        $type = $row['type'];
        $consume_data = $row['consume_data'];
        $consume_data_arr = json_decode($consume_data,true);

        if($status) {
        //$amount,$normal_amount,$overdue_amount,$customerId,$consume_id,$overdue_amount,$balance_amount_old,$insertId
        //更新用户账单和消费记录

/* 
            $sql ="select `type`,`repayment_time`,`amount` from `consume_history` where `id`='$consume_id' limit 1";
            $result = $mysqli->query($sql);
            $data_arr = $result->fetch_array(MYSQLI_ASSOC);
            $consume_type = $data_arr['type'];
            $repayment_time = $data_arr['repayment_time'];
           
            //分期期数，默认10期
            $sql = "select `id` from `consume_installment_history` where  `parent_id`='$consume_id'";
            $result = $mysqli->query($sql);
            $installment_rows = $result->num_rows;
            $installment_num = ($result) ? $installment_rows : 10;
            $amount_history = ceil($data_arr['amount']/$installment_num);
*/
            //这个版本，次月还款和分期还款不能混在一次一次性还清
            $consume_type =0;
            if($consume_data_arr) {
                foreach($consume_data_arr as $v) {
                    $consume_type = $v['type'];
                }
            }
            //交首付
            if($type ==2 && $consume_id>0) {
                //修改账单状态
                $mysqli->query("UPDATE `consume_history` SET `status`='8'  WHERE `status` ='2' AND `customer_id` = '$customerId' and `id`='$consume_id'");
                //调用渡渡接口，生成账单数据
                $xml_data = array(
                    "consume_id" => $consume_id,
                );
                $sign = genSign($xml_data);
                $url = "http://qtqapi.9maibei.com/Home/Order/orderRealPay";
                $xml_data['sign'] = $sign;
                curlPost($url,$xml_data);
            }
            //次月还款

            if($consume_type==1 && $type==1) {
                if($consume_data_arr) {
                    $normal_amount_all =0;
                    foreach($consume_data_arr as $v) {
                        $normal_amount = $v['amount'];
                        $overdue_amount = $v['overdue_amount'];
                        $repay_date  = $v['repay_date'];
                        $consume_id = $v['consume_id'];
                        /*
                        //还某次消费的欠款
                        //$CustomerBill->execute("UPDATE `customer_bill` SET `status`='1',`update_time`='".time()."',`paid`=`repayment_amount` WHERE `status` = 0 AND `customer_id` = '".$customerId."' and `id`='".$consume_id."'");
                        //$ConsumeHistory->where(['id'=>$consume_id,'status'=>array('neq',3),'customer_id'=>$customerId])->setField(['status'=>3,'update_time'=>time());
                        //本月还上个月
                        //$bill_date_last = $this->GetMonth();
                        */
                        $bill_date_last = date('Y-m');
                        $mysqli->query("UPDATE `customer_bill` SET `update_time`='".time()."',`status` = 1,`repayment_amount`=`repayment_amount`-$normal_amount ,`paid`=`paid`+ $normal_amount WHERE `customer_id` = '$customerId' and `type`='1' and `bill_date`='$bill_date_last' and `repayment_amount`>=$normal_amount");
                        //修改账单状态
                        $mysqli->query("UPDATE `consume_history` SET `status`='3',`update_time`='".time()."',`overdue_amount`='$overdue_amount' WHERE `status` <>3 AND `customer_id` = '$customerId' and `id`='$consume_id'");

                        $normal_amount_all = $normal_amount_all + $normal_amount;
                    }

                    //修改还款记录表本金字段
                    $mysqli->query("UPDATE `customer_bill_pay_log` SET `normal_amount`= $normal_amount WHERE  `id` = '$insertId'");

                    //增加可用金额（次月没有利息）
                    $mysqli->query("UPDATE `customer` SET `balance_amount`=`balance_amount` + $normal_amount WHERE  `id` = '$customerId' and `balance_amount`='$balance_amount_old'");
                }

            }

            if(($consume_type==2 || $consume_type==5) && $type==1) {
                $amount_history_all = 0; //回额度总金额（不包含利息）
                foreach($consume_data_arr as $v) {

                    $consume_id = $v['consume_id'];
                    $sql ="select `type`,`repayment_time`,`amount`,`consume_amount` from `consume_history` where `id`='$consume_id' limit 1";
                    $result = $mysqli->query($sql);
                    $consume_result_arr = $result->fetch_array(MYSQLI_ASSOC);
                    if($consume_type==2) {
                        $consume_amount = $consume_result_arr['amount'];
                    }
                    if($consume_type==5) {
                        $consume_amount = $consume_result_arr['consume_amount'];
                    }
                    if($v['installment_history']) {
                        //分期期数，默认10期
                        $sql = "select `id` from `consume_installment_history` where  `parent_id`='$consume_id'";
                        $result = $mysqli->query($sql);
                        $installment_rows = $result->num_rows;
                        $installment_num = ($result) ? $installment_rows : 10;
                        $amount_history = ceil($consume_amount/$installment_num);

                        foreach($v['installment_history'] as $v1) {

                            $normal_amount = $v1['amount'];//还款金额（分期含利息）
                            $overdue_amount = $v1['overdue_amount']; //逾期金额
                            $bill_date_last = date('Y-m');
                            $repay_date = $v1['repay_date'];

                            //还某次消费的欠款
                            //$bill_date_last = $this->GetMonth();
                            $bill_date_last = date('Y-m');
                            $mysqli->query("UPDATE `customer_bill` SET `update_time`='".time()."',`repayment_amount`=`repayment_amount`-$normal_amount ,`paid`=`paid`+ $normal_amount,`status`=1 WHERE  `customer_id` = '$customerId' and `type`='2' and `bill_date`='$bill_date_last' and `repayment_amount`>=$normal_amount");

                            //本月最后还款日期的订单（还款时间1号~10号）
                            $repayment_time = ($repay_date<>'') ? strtotime($repay_date." 00:00:00") : strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                            $parent_id = $consume_id;
                            $mysqli->query("UPDATE `consume_installment_history` SET `status`='1',`update_time`='".time()."',`overdue_amount`='$overdue_amount' WHERE `status`=0 AND `parent_id`='$parent_id' and `repayment_time`='$repayment_time'");

                            $data_arr = array();
                            $sql = "select `status` from `consume_installment_history` where  `parent_id`='$parent_id'";
                            $result = $mysqli->query($sql);
                            while($row = $result->fetch_array(MYSQLI_ASSOC)) {
                                $data_arr[] = array('status'=>$row['status']);
                            }
                            if($data_arr) {
                                $consume_status = 1;
                                foreach($data_arr as $v) {
                                    if($v['status']==0) {
                                        $consume_status = 0;
                                        break;
                                    }
                                }
                                if($consume_status) {
                                    $mysqli->query("UPDATE `consume_history` SET `status`='3',`update_time`='".time()."' WHERE `status` <>3 AND `customer_id` = '$customerId' and `id`='$consume_id'");
                                }
                            }
                            $amount_history_all = $amount_history_all + $amount_history;
                        }//foreach end
                        //更新消费记录的最后还款日期（bug 自然月还款）
                        $repayment_time_result = $mysqli->query("select `repayment_time` from `consume_installment_history` WHERE `status`='0' and `parent_id`='$parent_id' order by `repayment_time` asc limit 1");
                        $repayment_time_arr = $repayment_time_result->fetch_array(MYSQLI_ASSOC);
                        //$repayment_time_next = strtotime(date($this->GetMonth(0) .'-'. Constant::BILL_LAST_DAY . ' 00:00:00', time()));
                        $repayment_time_next = ($repayment_time_arr) ? $repayment_time_arr['repayment_time'] : 0;
                        $mysqli->query("UPDATE `consume_history` SET `repayment_time`='$repayment_time_next' WHERE  `customer_id` = '$customerId' and `id`='$consume_id'");
                    }
                }//foreach end
                if($amount_history_all > 0) {
                    //修改还款记录表本金字段
                    $mysqli->query("UPDATE `customer_bill_pay_log` SET `normal_amount`= $amount_history_all WHERE  `id` = '$insertId'");
                    if($consume_type==5) {
                        //增加可用金额（只加本金不算利息）
                        $mysqli->query("UPDATE `customer` SET `balance_cash_amount`=`balance_cash_amount` + $amount_history_all  WHERE  `id` = '$customerId' and `balance_cash_amount`='$balance_cash_amount_old'");

                        //还款后增加信用级别
                        $mysqli->query("UPDATE `customer` SET `credit_level`= `credit_level` +1  WHERE  `id` = '$customerId' and `credit_level`='$credit_level_old'");

                        //还款后发push
                        $xml_data = array(
                            "msg_type"=>"6",
                            "customer_id" => $customerId,
                        );
                        $sign = genSign($xml_data);
                        $url = "http://qtqapi.9maibei.com/Home/JPush/commonPush";
                        $xml_data['sign'] = $sign;
                        curlPost($url,$xml_data);
                    }
                    if($consume_type==2) {
                        //增加可用金额（只加本金不算利息）
                        $mysqli->query("UPDATE `customer` SET `balance_amount`=`balance_amount` + $amount_history_all  WHERE  `id` = '$customerId' and `balance_amount`='$balance_amount_old'");
                    }
                }
            }
        }
    }
    $mysqli->close();
}

function GetMonth($sign="1")
{
    //$ts = mktime(0, 0, 0, date('n') + 1, 10);
    //echo  date('Y-m-d', $ts);

    //得到系统的年月
    $tmp_date=date("Ym");
    //切割出年份
    $tmp_year=substr($tmp_date,0,4);
    //切割出月份
    $tmp_mon =substr($tmp_date,4,2);
    $tmp_nextmonth=mktime(0,0,0,$tmp_mon+1,1,$tmp_year);
    $tmp_forwardmonth=mktime(0,0,0,$tmp_mon-1,1,$tmp_year);
    if($sign==0){
        //得到当前月的下一个月 
        return $fm_next_month=date("Y-m",$tmp_nextmonth);        
    }else{
        //得到当前月的上一个月 
        return $fm_forward_month=date("Y-m",$tmp_forwardmonth);         
    }
}

function genSign(array $param) {
    //0. 删除原数据中自带的sign值,防止干扰计算结果
    unset($param['sign']);
    //1. 按key由a到z排序
    ksort($param);
    foreach ($param as $key => $value) {
        if (is_array($value)) {
            $param[$key] = $this->genSign($value);
        }
    }
    //2. 生成以&符链接的key=value形式的字符串
    $paramString = urldecode(http_build_query($param));

    //3. 拼接我们的服务秘钥，并md5加密
    $sign = md5($paramString . 'xxxx.xxxxx.com');
    return $sign;
}

function curlPost($url,$xml_data) {
    $ch=curl_init($url); 
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_data));
    $response = curl_exec($ch);
    if(curl_errno($ch))
    {
        print curl_error($ch);
    }
    curl_close($ch);
}